package com.chj.resources;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.chj.utils.KafkaUtils;

@RestController
public class TestResource {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private KafkaTemplate<String, String> kafkaTemplate;

	@RequestMapping(value = "/send/{topic}/{key}", method = RequestMethod.POST)
	public ResponseEntity<?> sendKafka(@PathVariable("topic") String topic, @PathVariable("key") String key, @RequestBody String message) {
		try {
			logger.info("kafka的消息 topic={}, key={}, message={}", topic, key, message);
			// kafkaTemplate.send(topic, key, message);
			KafkaUtils.sendMessage(topic, key, message);
			logger.info("发送kafka成功.");
			return new ResponseEntity<String>(HttpStatus.OK);
		} catch (Exception e) {
			logger.error("发送kafka失败", e);
			return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

}
